package util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 黄衡熙
 * @version 1.0
 */
public class CookieUtil {
    /*
    * 添加Coookie
    * @param name
    * @param value
    * @param response
    * */
    public static void addCookie(String name, String value, HttpServletResponse response){
        Cookie cookie=new Cookie(name,value);
        response.addCookie(cookie);
    }
    /*
    * 添加一个指定生存时间的cookie
    * @param name
    * @param value
    * @param maxAge
    * @param response
    * */
    public static void addCookie(String name,String value,int maxAge,HttpServletResponse response){
        Cookie cookie=new Cookie(name,value);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
    /**
     * 删除指定cookie
     * @param name
     * @param response
     *首先找到key，值设置随意，相当于覆盖然后生存时间设置为0，既生成立即毁灭，即可完成删除
     */
    public static void removeCookie(String name, HttpServletResponse response) {
        addCookie(name, "", 0, response);
    }

    /**
     * 修改指定cookie
     * @param name
     * @param value
     * @param response
     * key相同会覆盖，相当于修改
     */
    public static void modifyCookie(String name, String value, HttpServletResponse response) {
        addCookie(name, value, response);
    }

    /**
     * 修改指定cookie,并设置修改后cookie的生存时间
     * @param name
     * @param value
     * @param maxAge
     * @param response
     */
    public static void modifyCookie(String name, String value, int maxAge, HttpServletResponse response) {
        addCookie(name, value, maxAge, response);
    }

    /*
    * 根据指定的名称在请求中查找对应的 Cookie，并返回其值
    * 查询所有遍历
    * */
    public static String findByName(String name, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
